package com.atguigu.tingshu.user.api;

import cn.binarywang.wx.miniapp.api.WxMaService;
import cn.binarywang.wx.miniapp.bean.WxMaJscode2SessionResult;
import com.atguigu.tingshu.common.constant.KafkaConstant;
import com.atguigu.tingshu.common.constant.RedisConstant;
import com.atguigu.tingshu.common.login.GuiGuLogin;
import com.atguigu.tingshu.common.result.Result;
import com.atguigu.tingshu.common.service.KafkaService;
import com.atguigu.tingshu.common.util.AuthContextHolder;
import com.atguigu.tingshu.model.user.UserInfo;
import com.atguigu.tingshu.user.service.UserInfoService;
import com.atguigu.tingshu.vo.user.UserInfoVo;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.extern.slf4j.Slf4j;
import me.chanjar.weixin.common.error.WxErrorException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

@Tag(name = "微信授权登录接口")
@RestController
@RequestMapping("/api/user/wxLogin")
@Slf4j
public class WxLoginApiController {

    @Autowired
    private UserInfoService userInfoService;

    @Autowired
    private RedisTemplate redisTemplate;

    //  自己注入一个WxMaService
    @Autowired
    private WxMaService wxMaService;

    @Autowired
    private KafkaService kafkaService;

    /**
     * 将用户信息存储到缓存。
     * @param userId
     * @return
     */
    @Operation(summary = "手动获取token")
    @GetMapping("/getToken/{userId}")
    public Result login(@PathVariable Long userId) {
        //  获取数据库中的用户Id 26
        UserInfo userInfo = userInfoService.getById(userId);
        String token = UUID.randomUUID().toString().replaceAll("-", "");
        //  26 存储到缓存。
        redisTemplate.opsForValue().set(RedisConstant.USER_LOGIN_KEY_PREFIX+token, userInfo, RedisConstant.USER_LOGIN_REFRESH_KEY_TIMEOUT, TimeUnit.SECONDS);
        Map<String, Object> map = new HashMap<>();
        map.put("token", token);
        return Result.ok(map);
    }

    //  http://127.0.0.1/api/user/wxLogin/wxLogin/0f1K9i1w3lQsU13RyG0w3l3qta3K9i1h
    @Operation(summary = "微信登录")
    @GetMapping("/wxLogin/{code}")
    public Result wxLogin(@PathVariable String code){
        //  调用服务层方法.
        WxMaJscode2SessionResult sessionInfo = null;
        try {
            sessionInfo = wxMaService.getUserService().getSessionInfo(code);
        } catch (WxErrorException e) {
            throw new RuntimeException(e);
        }
        //  获取到openId
        String openid = sessionInfo.getOpenid();
        //  select * from user_info where open_id = ?
        UserInfo userInfo = userInfoService.getOne(new LambdaQueryWrapper<UserInfo>().eq(UserInfo::getWxOpenId, openid));
        //  判断当前用户对象
        if (null == userInfo){
            //  说明用户未注册过.
            userInfo = new UserInfo();
            userInfo.setWxOpenId(openid);
            userInfo.setNickname("听友："+ UUID.randomUUID().toString().replaceAll("-",""));
            userInfo.setAvatarUrl("https://oss.aliyuncs.com/aliyun_id_photo_bucket/default_handsome.jpg");
            //  保存数据
            userInfoService.save(userInfo);
            //  用户账户初始化; service-account 第一种方式：远程调用; 要保证数据一致性：分布式事务： 第二种方式：异步 userInfo.getId();
            kafkaService.sendMsg(KafkaConstant.QUEUE_USER_REGISTER,userInfo.getId().toString());

        }
        //  存储用户信息，并返回token;
        String token = UUID.randomUUID().toString().replaceAll("-","");
        String loginKey = RedisConstant.USER_LOGIN_KEY_PREFIX+token;
        //  存储数据
        redisTemplate.opsForValue().set(loginKey,userInfo,RedisConstant.USER_LOGIN_KEY_TIMEOUT, TimeUnit.SECONDS);
        //  创建map 存储token
        HashMap<String, Object> map = new HashMap<>();
        map.put("token",token);
        //  返回数据 xxx.token=token  result.data=token;
        return Result.ok(map);
    }


    //  http://127.0.0.1/api/user/wxLogin/getUserInfo
    /**
     * 根据用户Id获取到用户数据
     * @return
     */
    @GuiGuLogin
    @Operation(summary = "获取登录信息")
    @GetMapping("getUserInfo")
    public Result getUserInfo(){
        //  获取用户Id
        Long userId = AuthContextHolder.getUserId();
        //  调用服务层方法. select * from user_info id = ?;
        UserInfoVo userInfoVo = this.userInfoService.getUserInfoById(userId);
        //        UserInfo userInfo = this.userInfoService.getById(userId);
        //        UserInfoVo userInfoVo =
        //  返回数据
        return Result.ok(userInfoVo);
    }

    /**
     * 修改用户信息
     * @param userInfoVo
     * @return
     */
    @GuiGuLogin
    @Operation(summary = "修改用户信息")
    @PostMapping("/updateUser")
    public Result updateUser(@RequestBody UserInfoVo userInfoVo){
        //  调用服务层方法. nickname avatarUrl 修改的内容：有条件：在哪?
        Long userId = AuthContextHolder.getUserId();
        this.userInfoService.updateUser(userInfoVo,userId);
        //  返回数据
        return Result.ok();
    }

}
